<?php
include_once("../includes/common.php");
include_once("../class/User.class.php");
include_once("../class/Explore.class.php");
require_once("../islogin.php");

if ($islogin!=1){
    header('Location: /login.php');
    exit;
}

$menuavatar = !$user_info["message"]["avatar"] ? "/data/avatar/default.jpg" : $user_info["message"]["avatar"];
$pageName = "笔记编辑";
$edit_note = 1;
$info = 0;
$msg = null;
$noteisme = false;

$explore = new Explore();
if (isset($_GET['nid'])){
    $note_info = json_decode($explore->getIdNotes($_GET['nid']),true);
    if($note_info["user_id"]!=$user_info['message']['user_id']){
        exit('nid error 无权限');
    }

    $title = $note_info["title"];
    $content = $note_info["content"];
    $tags = $note_info["tags"];
    $images = $note_info["image"];
    // 将图片路径字符串分割为数组
    $imageArray = explode(',', $images);

    foreach ($imageArray as &$image) {
        if (substr($image, 0, 1) !== '/') {
            // 如果路径不以 '/' 开头，则在前面加上 '/'
            $image = '/' . $image;
        }
    }

    $images = implode(',', $imageArray);
    $noteisme = true;
}


if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if(!isset($_GET['nid'])){
        $title = $_POST['title'] ?? '';
        $content = $_POST['content'] ?? '';
        $tags = $_POST['tags'] ?? '';
        $tags = preg_replace('/[ ;]+/', ',', $tags); // 替换分号和空格为英文逗号
        $tags = trim($tags, ',');

        $images = $_POST['images'] ?? '';
        $res = json_decode($explore->postNote($user_info['message']['user_id'], $title, $content, $images, $tags),true);


        if ($res["status"] == 200) {
            header('location: /control/notelist.php');
            exit;
        }else{
            $info = 1;
            $msg = $res["message"];
        }
    }else{
        if ($noteisme){
            $title = $_POST['title'] ?? '';
            $content = $_POST['content'] ?? '';
            $tags = $_POST['tags'] ?? '';
            $tags = preg_replace('/[ ;]+/', ',', $tags); // 替换分号和空格为英文逗号
            $tags = trim($tags, ',');
            //var_dump($tags);exit();

            $images = $_POST['images'] ?? '';

            $res = json_decode($explore->changeNote($_GET['nid'],$title,$content,$images,$tags),true);
            //var_dump($res);exit('error');
            if ($res["status"] == 200) {
                header('location: /control/notelist.php?type=nocheck');
                exit;
            }else{
                $info = 1;
                $msg = $res["message"];
            }
        }else{
            exit('nid 无权限');
        }
    }

}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <?php require_once('head.php'); ?>

    <link rel="stylesheet" href="/static/css/message.css">
    <style>
        .file-preview{
            position: relative;
            display: inline-flex;
        }
        #uploadResult {
            border-radius: 10px;
            border: 1px solid #ecf2fe; /* 边框，仅用于视觉效果 */
            padding-top: 10px;
            width: 100%;
            text-align: center;
        }
        .file-preview video{
            border-radius: 10px;
        }
        /*
        .image-upload-deleteBtn{
            position: absolute;
            width: 19px;
            height: 19px;
            background-color: rgba(108, 108, 108, 0.37);
            border-radius: 50%;
            right: 7px;
            top: 8px;
        }
        .image-upload-deleteBtn:hover{
            background-color: rgba(51,51,51,0.08);
        }*/
        .file-preview img{
            object-fit: cover;
            border-radius: 5px;
        }
    </style>
</head> 
<body>
    
<!--==================== Preloader Start ====================-->
  <div class="preloader">
    <div class="loader"></div>
  </div>
<!--==================== Preloader End ====================-->

<!--==================== Sidebar Overlay End ====================-->
<div class="side-overlay"></div>
<!--==================== Sidebar Overlay End ====================-->

<?php require_once('user_menu.php'); ?>
    <div class="dashboard-main-wrapper">
        <?php require_once('top_navbar.php'); ?>
        <div class="dashboard-body">

            <!-- Course Tab Start -->
            <div class="card">
                <div class="card-header border-bottom border-gray-100 flex-align gap-8">
                    <h5 class="mb-0">发布笔记</h5>

                </div>
                <div class="card-body">
                    <form action="" method="post">
                        <div class="row gy-20">
                            <div class="col-xxl-12">
                                <div id="fileUpload" class="fileUpload image-upload"></div>
                            </div>
                            <div class="col-xxl-12">
                                <div id="uploadResult">
                                    <?php
/*                                    if (!empty($images)) {
                                        // 将 images 按逗号分割为数组
                                        $imageArray = explode(',', $images);

                                        // 遍历每个图像或视频文件
                                        foreach ($imageArray as $image) {
                                            $image = trim($image); // 去掉前后空格

                                            // 检查文件类型
                                            if (strpos($image, '.mp4') !== false) {
                                                // 如果是 MP4 文件，输出视频标签
                                                echo '<div class="file-preview">
                                            <video controls="" style="width:300px;">
                                                <source src="' . htmlspecialchars($image) . '" type="video/mp4">
                                                您的浏览器不支持视频标签。
                                            </video>
                                            <button type="button" class="image-upload__deleteBtn" data-image-url="' . htmlspecialchars($image) . '" data-file-type="video/mp4"><i class="ph ph-x"></i></button>
                                          </div>';
                                                                    } else {
                                                                        // 否则，输出图片标签
                                                                        echo '<div class="file-preview"> 
                                            <img src="' . htmlspecialchars($image) . '" alt="' . htmlspecialchars($image) . '" class="uploaded-image" style="width:100px;height:100px;margin:5px;">
                                            <button type="button" class="image-upload__deleteBtn" data-image-url="' . htmlspecialchars($image) . '" data-file-type="image"><i class="ph ph-x"></i></button>
                                          </div>';
                                            }
                                        }
                                    }
                                    */?>
                                    <!--<div class="file-preview">
                                        <img src="blob:xx/10240982-8a83-4f18-b710-3ca583e0d97b" alt="_1_暮雨玖黎_来自小红书网页版.jpg" class="uploaded-image" style="width:100px;height:100px;margin:5px;">
                                        <button type="button" class="image-upload-deleteBtn"><i class="ph ph-x"></i></button>
                                    </div>-->

                                </div>
                            </div>
                            <div class="col-xxl-12">
                                <div class="row g-20">
                                    <div class="col-sm-12">
                                        <label for="courseTitle" class="h5 mb-8 fw-semibold font-heading">正文内容 </label>
                                        <div class="position-relative">
                                            <input value="<?php echo $title?>" name="title" type="text" class="text-counter placeholder-14 form-control" maxlength="20" id="courseTitle" placeholder="填写标题会有更多赞哦 ~">
                                            <div class="text-gray-400 position-absolute inset-inline-end-0 top-50 translate-middle-y me-16">
                                                <span id="current">0</span>
                                                <span id="maximum">/ 20</span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="position-relative mt-10">
                                        <textarea maxlength="1000" name="content" class="form-control placeholder-14" style="height: 320px;line-height: 1.5;" placeholder="在这里输入正文描述，真诚有价值的分享予人温暖"><?php echo htmlspecialchars(str_replace("\n", "",  preg_replace('/(<br\s*\/?>)+/', "\n", $content)));?></textarea>

                                    </div>
                                    <div class="position-relative mt-10">
                                        <input value="<?php echo $tags?>" name="tags" type="text" class="text-counter placeholder-14 form-control" maxlength="255" id="" placeholder="文章标签可用英文逗号、空格、英文分号分隔">
                                    </div>
                                    <div class="position-relative mt-10" style="display:none;">
                                        <input value="<?php //echo $images?>" name="images" type="text" class="text-counter placeholder-14 form-control" maxlength="1000" id="" placeholder="图片地址">
                                    </div>

                                </div>
                            </div>
                            <div class="flex-align justify-content-end gap-8">
                                <button type="submit" class="btn btn-main rounded-pill py-9">发布</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            <!-- Course Tab End -->
        </div>

        <?php require_once('footer.php'); ?>

    </div>

<script src="/static/js/message.min.js"></script>
<?php require_once('foot.php'); ?>
<?php if ($info==1){?>
    <script>
        Qmsg.info("<?php echo $msg;?>");
    </script>
<?php }?>

<script>

    var images = '<?php echo $images;?>';
    var imageArray = images.split(','); // 将路径分割成数组

    //console.log(images)
    imageArray.forEach(function(imagePath) {
        var fileName = imagePath.split('/').pop(); // 获取文件名
        var fileExtension = fileName.split('.').pop().toLowerCase(); // 获取文件后缀
        var post_file;

        // 判断文件类型
        if (['jpg', 'jpeg', 'png', 'gif'].includes(fileExtension)) {
            // 如果是图片类型，创建对应的 File 对象
            post_file = new File([""], fileName, { type: "image/*" }); // 设置为 image/*
        } else if (fileExtension === 'mp4') {
            // 如果是 MP4 视频类型，创建对应的 File 对象
            post_file = new File([""], fileName, { type: "video/mp4" });
        }

        // 调用全局函数
        if (post_file) {
            window.displayUploadedImages(imagePath, post_file);
        }
    });


</script>
    </body>
</html>